package com.example.demo.core;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author ghl
 * @version 1.0
 * @date 2022/9/21 12:18
 * @description 摘要
 */
public class ResultDTO<T> implements Serializable {
    private Boolean success;
    private String code;
    private String message;
    private T data;

    public ResultDTO() {
        this.success = Boolean.TRUE;
        this.code = "OK";
        this.message = "OK";
    }

    public ResultDTO(T data) {
        this.success = Boolean.TRUE;
        this.code = "OK";
        this.message = "OK";
        this.data = data;
    }

    /**
     * @deprecated
     */
    @Deprecated
    public static <T> ResultDTO<T> newResult() {
        return empty();
    }

    /**
     * @deprecated
     */
    @Deprecated
    public static <T> ResultDTO<T> newResult(T data) {
        return ok(data);
    }


    public static <T> ResultDTO<T> empty() {
        return new ResultDTO();
    }

    public static <T> ResultDTO<T> ok(T data) {
        return new ResultDTO(data);
    }


    public static <T> ResultDTO<T> err(String code, String msg) {
        ResultDTO<T> inst = new ResultDTO();
        inst.code = code;
        inst.message = msg;
        inst.success = false;
        return inst;
    }

    public static <T> ResultDTO<T> err(String msg) {
        return err("RY00", msg);
    }


    public static <R, D> ResultDTO<List<D>> map(Collection<R> origin, Function<R, D> mapper) {
        List<D> list = (List) origin.stream().map(mapper).collect(Collectors.toList());
        return new ResultDTO(list);
    }


    public Boolean getSuccess() {
        return this.success;
    }

    public void setSuccess(Boolean success) {
        this.success = success;
    }

    public String getCode() {
        return this.code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return this.message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return this.data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "ResultDTO{" +
                "success=" + success +
                ", code='" + code + '\'' +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }
}
